package main

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"net"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var peers *PeerTable

func main() {
	rand.Seed(time.Now().UnixNano())
	fmt.Println("A number from 1-100", rand.Float64())
	//创建监听退出chan
	c := make(chan os.Signal)
	//监听指定信号 ctrl+c kill
	signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGUSR1, syscall.SIGUSR2)
	go func() {
		for s := range c {
			switch s {
			case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT:
				fmt.Println("退出", s)
				ExitFunc()
			case syscall.SIGUSR1:
				fmt.Println("usr1", s)
			case syscall.SIGUSR2:
				fmt.Println("usr2", s)
			default:
				fmt.Println("other", s)
			}
		}
	}()
	peers = NewPeerTable()
	ips, _ := GetLocalIP()
	mac, _ := GetLocalMac(ips[0])
	fmt.Println(ips, mac)
	udp := NewUDP(ips, 8989)
	go udp.NewServer(OnPing)
	// if len(ips) > 0 {
	// 	udp := NewUDP(ips, 8989)
	// 	go udp.NewServer()
	// }
	HTTPServer()
}
func OnPing(remote *net.UDPAddr, data []byte) {
	var peer Peer
	var datastr = string(data)
	fmt.Println(remote, datastr)
	err := json.Unmarshal([]byte(datastr), &peer)
	if err != nil {
		fmt.Println(err)
	}
	peer.Ip = remote.IP.String()
	peers.Set(&peer)
	return
}
func ExitFunc() {
	fmt.Println("开始退出...")
	fmt.Println("执行清理...")
	fmt.Println("结束退出...")
	os.Exit(0)
}
